package hw.ats.news.ds;

import hw.ats.news.model.Cmt;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.humanwares.util.StringUtil;

import android.util.Log;

public class CmtParser {
	private final static String TAG = "CmtParser";
    private URL feedUrl;
    
    public CmtParser(String feedUrl){
        try {
            this.feedUrl = new URL(feedUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    private InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    private String textNodeValue(Node node) {
    	if (node == null)
    		return null;
    	
    	Node cnode = node.getFirstChild();
    	if (cnode == null)
    		return null;
    	
    	return cnode.getNodeValue();
    }
    
    private int textNodeIntValue(Node node) {
    	return StringUtil.intValue(textNodeValue(node));
    }
    
    private long textNodeLongValue(Node node) {
    	return StringUtil.longValue(textNodeValue(node));
    }
    
    public List<Cmt> parse() {
    	Log.d(TAG, "S--------------------------------------------------------");
    	
    	List<Cmt> list = new ArrayList<Cmt>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document dom = builder.parse(this.getInputStream());
			
			// <response>
			Element root = dom.getDocumentElement(); 
			Log.d(TAG, "nodeName=" + root.getNodeName());
			
			// <comment>...</comment>
			NodeList items = root.getChildNodes();
			if (items.getLength() == 0)
				return null; // 데이터 없음
			
			for (int j = 0; j < items.getLength(); j++) {
				Node item = items.item(j);
				if (!"comment".equals(item.getNodeName()))
					continue;
				
				Log.d(TAG, "item="+item.getNodeName());
				
				// <comment> 자식노드
				NodeList citems = item.getChildNodes();
				if (citems.getLength() == 0)
					continue;
				
				Cmt c = new Cmt();
				list.add(c);
				
				for (int i = 0; i < citems.getLength(); i++) {
					Node citem = citems.item(i);
					if (citem == null)
						continue;
					
					Log.d(TAG, "citem="+citem.getNodeName());
					
					String nodeName = citem.getNodeName();
					if ("id".equals(nodeName)) {
						c.uid = textNodeIntValue(citem);
						Log.d(TAG, "uid="+c.uid+"-=================");
					} else if ("entry".equals(nodeName)) {
						c.news_uid = textNodeIntValue(citem);
					} else if ("content".equals(nodeName)) {
						c.body = textNodeValue(citem);
					} else if ("written".equals(nodeName)) {
						c.regdate = new Date(textNodeLongValue(citem) * 1000L);
					} else if ("name".equals(nodeName)) {
						c.author = textNodeValue(citem);
					} else if ("homepage".equals(nodeName)) {
						c.homepage = textNodeValue(citem);
					}
					
					// 서브댓글
					else if ("comment".equals(nodeName)) {
						NodeList sitems = citem.getChildNodes();
						if (sitems.getLength() == 0)
							continue;
						
						Cmt s = new Cmt();
						s.pid = c.uid; // 부모 댓글 번호
						list.add(s); // depth를 두지 않고 plain하도록
//						if (c.children == null) {
//						c.children = new ArrayList<Cmt>();
//						c.children.add(s);
//					}

						
						for (int k = 0; k < sitems.getLength(); k++) {
							Node sitem = sitems.item(k);
							if (sitem == null)
								continue;
							
							String snodeName = sitem.getNodeName();
							if ("id".equals(snodeName)) {
								s.uid = textNodeIntValue(sitem);
							} else if ("entry".equals(snodeName)) {
								s.news_uid = textNodeIntValue(sitem);
							} else if ("content".equals(snodeName)) {
								s.body = textNodeValue(sitem);
							} else if ("written".equals(snodeName)) {
								s.regdate = new Date(textNodeLongValue(sitem) * 1000L);
							} else if ("name".equals(snodeName)) {
								s.author = textNodeValue(sitem);
							} else if ("homepage".equals(snodeName)) {
								s.homepage = textNodeValue(sitem);
							}
						}
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
        
		Log.d(TAG, "list="+list);
		Log.d(TAG, "E--------------------------------------------------------\n\n");
		return list;
    }
}
